//
//  WJPDFImageAnnotation.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/25.
//

import UIKit
import PDFKit

class WJPDFImageAnnotation: PDFAnnotation {
    private var image: UIImage?
    
    init(image: UIImage?, bounds: CGRect) {
        self.image = image
        super.init(bounds: bounds, forType: .stamp, withProperties: nil)
        self.color = .clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(with box: PDFDisplayBox, in context: CGContext) {
        guard let image = image else { return }
        
        // 保持宽高比绘制图像
        drawImagePreservingAspectRatio(image, in: bounds, context: context)
    }
    
    private func drawImagePreservingAspectRatio(_ image: UIImage, in rect: CGRect, context: CGContext) {
        context.saveGState()
        
        let imageSize = image.size
        let targetSize = rect.size
        
        // 计算适合目标矩形的大小（保持宽高比）
        let imageAspect = imageSize.width / imageSize.height
        let targetAspect = targetSize.width / targetSize.height
        
        var drawRect = rect
        
        if imageAspect > targetAspect {
            // 图像比目标区域宽，以宽度为准缩放
            let scale = targetSize.width / imageSize.width
            let scaledHeight = imageSize.height * scale
            drawRect.size.height = scaledHeight
            drawRect.origin.y += (targetSize.height - scaledHeight) / 2.0
        } else {
            // 图像比目标区域高，以高度为准缩放
            let scale = targetSize.height / imageSize.height
            let scaledWidth = imageSize.width * scale
            drawRect.size.width = scaledWidth
            drawRect.origin.x += (targetSize.width - scaledWidth) / 2.0
        }
        
        // 绘制图像
        if let cgImage = image.cgImage {
            context.draw(cgImage, in: drawRect)
        }
        
        context.restoreGState()
    }
}
